import 'dart:io';

import 'package:easy_video/controller/index/index.dart';
import 'package:easy_video/internal/api/user_api.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../model/user_model.dart';

class AppController {
  AppController._internal();

  late String appName;

  late String buildNumber;

  late String version;

  late String platform;

  bool isLogin = false;

  late UserModel user = UserModel();

  late String token;

  late SharedPreferences prefs;

  static final AppController _instance = AppController._internal();

  factory AppController() {
    return _instance;
  }

  Future<void> setUser(UserModel user, String token) async {
    this.user = user;
    this.token = token;
    this.prefs.setString("_user_info_", user.toJson().toString());
    this.prefs.setString("_user_token_", token);
    this.isLogin = true;
    List<GetxController?> list = [
      Get.isRegistered<IndexController>() ? Get.find<IndexController>() : null,
    ];
    for (var controller in list) {
      if (controller != null) {
        controller.update();
      }
    }
  }

  Future<void> loadUser() async {
    String? token = await this.prefs.getString("_user_token_");
    if (token != null && token.isNotEmpty) {
      var res = await UserApi().info();
      await this.setUser(
        UserModel.fromJson(res.data["data"]),
        res.data["data"]["token"],
      );
    }
  }

  Future<void> exitUser() async {
    this.user = UserModel();
    this.token = "";
    this.isLogin = false;
    this.prefs.remove("_user_info");
    this.prefs.remove("_user_token_");
  }

  Future<void> init() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    this.prefs = await SharedPreferences.getInstance();
    this.appName = packageInfo.appName;
    this.buildNumber = packageInfo.buildNumber;
    this.version = packageInfo.version;
    if (kIsWeb) {
      this.platform = "web";
    } else {
      this.platform = Platform.operatingSystem;
    }
    return;
  }
}
